package com.tid.hbasees.repo;


import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tid.hbasees.model.Event;
import com.tid.hbasees.utils.hbase.HBaseHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Scan;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Component
public class EventRepo {

    public static String TABLE_NAME = "event";
    public static String INDEX_TABLE_NAME_1 = TABLE_NAME + "_index1";
    public static String INDEX_TABLE_NAME_2 = TABLE_NAME + "_index2";
    public static String INDEX_TABLE_NAME_3 = TABLE_NAME + "_index3";


    @Resource(name = "hbaseHelper")
    private HBaseHelper hbaseHelper;

    private HTableInterface getTable() throws IOException {
        return hbaseHelper.getTable(TABLE_NAME);
    }

    public void save(List<Event> events) {

    }

    public List<Event> getEvents(long startTime, long endTime, String nodeId, String networkType) throws ExecutionException, InterruptedException {

        List<Map<String, Scan>> conditions = Lists.newLinkedList();

        Map<String, Scan> scans = Maps.newHashMap();
        scans.put(DeviceRepo.INDEX_TABLE_NAME, hbaseHelper.buildTypicalScan(nodeId, startTime, endTime));
        Map<String, Scan> scans2 = Maps.newHashMap();
        for (String rowkey : hbaseHelper.indexScanResult(scans)) {
            String[] pieces = StringUtils.split(rowkey, HBaseHelper.ROWKEY_SEP);
            String deviceId = pieces[pieces.length - 1];
            scans2.put(INDEX_TABLE_NAME_1, hbaseHelper.buildTypicalScan(deviceId, startTime, endTime));
            scans2.put(INDEX_TABLE_NAME_2, hbaseHelper.buildTypicalScan(deviceId, startTime, endTime));
        }

        conditions.add(scans2);


        Map<String, Scan> networkScans = Maps.newHashMap();
        scans.put(NetworkRepo.INDEX_TABLE_NAME, hbaseHelper.buildTypicalScan(networkType, startTime, endTime));
        Map<String, Scan> scans3 = Maps.newHashMap();
        for (String rowkey : hbaseHelper.indexScanResult(networkScans)) {
            String[] pieces = StringUtils.split(rowkey, HBaseHelper.ROWKEY_SEP);
            String netId = pieces[pieces.length - 1];
            scans3.put(INDEX_TABLE_NAME_3, hbaseHelper.buildTypicalScan(netId, startTime, endTime));
        }


        conditions.add(scans3);

        return hbaseHelper.multiScan(conditions, TABLE_NAME, Event.class);
    }
}
